<template>
  <div class="setting-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row>
        <el-col :span="12" :xs="24">
          <el-form ref="form" :model="userData" label-width="80px">
            <el-form-item label="用户id :">{{ userData.id }}</el-form-item>
            <el-form-item label="手机 :">{{ userData.mobile }}</el-form-item>
            <el-form-item label="媒体名称 :">
              <el-input v-model="userData.name"></el-input>
            </el-form-item>
            <el-form-item label="媒体介绍 :">
              <el-input type="textarea" v-model="userData.intro"></el-input>
            </el-form-item>
            <el-form-item label="邮箱 :">
              <el-input v-model="userData.email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSave">保存</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12" :xs="24">
          <label for="uploadImage">
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :on-change="onChange"
              ref="upload"
              :headers="uploadHeaders"
              :http-request="uploadImageFile"
              :auto-upload="false"
              :on-success="onUploadImage"
              @closed="onDialogClosed"
            >
              <img v-if="userData.photo" :src="userData.photo" class="avatar" :v-model="userData.photo">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <el-button type="primary" size="mini">修改头像<i class="el-icon-upload el-icon--right"></i></el-button>
            </el-upload>
          </label>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      title="修改头像"
      width="25%"
      :visible.sync="dialogUploadVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @opened="onDialogOpened"
    >
      <div class="cropper-box">
        <el-row>
          <el-col :span="14">
            <el-image
              style="width: 260px; height: 260px"
              :src="afterUploadImage"
              fit="cover"
              ref="cropper-image"
              referrer-policy
            >
            </el-image>
          </el-col>
          <el-col :span="10">
            <el-image
              style="width: 120px; height: 120px"
              :src="afterUploadImage"
              fit="cover">
            </el-image>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onUpdatePhoto">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 导入个人设置api接口
import { user, editUser, editAvatar } from '@/api/setting'

// 导入全局通信模块
import globalBus from '@/utils/global-bus'

// 导入裁剪模块
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

export default {
  name: 'appSetting',
  data () {
    const user = JSON.parse(window.localStorage.getItem('User'))
    return {
      // 用户个人信息
      userData: {
        email: '',
        id: null,
        intro: '',
        mobile: null,
        name: '',
        photo: ''
      },
      afterUploadImage: '', // 上传之后的图片
      dialogUploadVisible: false, // 对话框默认关闭状态
      cropper: null, // 裁剪对象
      uploadHeaders: { // 设置请求头
        Authorization: `Bearer ${user.token}`
      }
    }
  },
  methods: {
    // 获取用户个人信息
    async getUserInfo () {
      const res = await user()
      try {
        this.userData = res.data.data
      } catch (err) {
        return Promise.reject(err)
      }
    },
    // 修改头像触发的回调函数
    onChange (file, fileList) {
      // 弹窗裁剪
      this.dialogUploadVisible = true
      this.afterUploadImage = URL.createObjectURL(file.raw)
    },
    // dialog对话框打开动画结束时的回调
    onDialogOpened () {
      // 获取image,DOM元素节点
      const image = this.$refs['cropper-image'].$el.firstChild
      // 初始化裁剪器
      this.cropper = new Cropper(image, {
        viewMode: 1,
        dragMode: 'none',
        aspectRatio: 1,
        cropBoxResizable: false
      })
    },
    // dialog对话框关闭动画结束时的回调
    onDialogClosed () {
      // 关闭dialog,销毁裁剪器, 初始化裁剪图片
      this.cropper.destroy()
    },
    // 上传之前操作
    uploadImageFile () {
      this.cropper.getCroppedCanvas().toBlob(async (file) => {
        const fd = new FormData()
        fd.append('photo', file)
        // 发送请求修改头像
        const res = await editAvatar(fd)
        try {
          // 修改成功,关闭对话框
          this.dialogUploadVisible = false
          // 更新视图, 将上传之后的图片覆盖掉之前的图片
          this.userData.photo = res.data.data.photo

          // 注册全局通信组件,将数据传给layout组件
          globalBus.$emit('upload-user', this.userData)
        } catch (err) {
          return Promise.reject(err)
        }
      })
    },
    // 保存修改的头像
    onUpdatePhoto () {
      // 点击确定按钮开始上传
      this.$refs.upload.submit()
    },
    // 修改头像成功后的回调函数
    onUploadImage () {
      this.$message({
        type: 'success',
        message: '修改头像成功'
      })
    },
    // 保存用户个人信息
    async onSave () {
      // edittUser(data{name,intro,email})必须
      await editUser({
        name: this.userData.name,
        intro: this.userData.intro,
        email: this.userData.email
      })
      try {
        // 提示用户个人信息更新成功
        this.$message({
          type: 'success',
          message: '保存成功'
        })

        // 注册全局通信组件,将数据传给layout组件
        globalBus.$emit('upload-user', this.userData)
      } catch (err) {
        return Promise.reject(err)
      }
    }
  },
  created () {
    this.getUserInfo()
  }
}
</script>
<style lang="less">
.setting-container{
  .box-card{
    .el-row{
      .el-col{
        &:nth-child(2){
          .avatar-uploader .el-upload {
            height: 178px;
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            button{
              margin-top: 10px;
            }
          }
          .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
          }
          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
          }
          .avatar {
            width: 178px;
            height: 178px;
            display: block;
          }
          text-align: center;
          .avatar-image{
            img{
              width: 180px;
              height: 180px;
            }
          }
        }
      }
    }
  }
}
.el-dialog{
  .cropper-box{
    .el-row{
      .el-col-10{
        text-align: center;
        .el-image{
          border-radius: 50%;
        }
      }
    }
  }
}
</style>
